import { onMounted, onUnmounted, ref } from "vue"
import {throttle} from "underscore"

// 方式一：回调函数
// export default function useScroll(callback){
//   const scrollListenerHandle = () => {
//     const clientHeight = document.documentElement.clientHeight
//     const scrollTop = document.documentElement.scrollTop
//     const scrollHeight = document.documentElement.scrollHeight
//     if(clientHeight + scrollTop >= scrollHeight){
//       if(callback) callback()
//     }
//   }

//   onMounted(() => {
//     window.addEventListener("scroll", scrollListenerHandle, true)
//   })

//   onUnmounted(() => {
//     window.removeEventListener("scroll", scrollListenerHandle, true)
//   })
// }

// 适用于监听window和盒子内的滚动
// 方式二：响应式变量   
// 应用场景：节流应用于滚动功能
export default function useScroll(elRef){
  let el = window
  const isReachBottom = ref(false)
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)
  const scrollListenerHandle = throttle(() => {
    if(el === window){
      clientHeight.value = document.documentElement.clientHeight
      scrollTop.value = document.documentElement.scrollTop
      scrollHeight.value = document.documentElement.scrollHeight
    } else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
    }
    // console.log(clientHeight.value, scrollTop.value, scrollHeight.value);
    if(clientHeight.value + scrollTop.value >= scrollHeight.value){
      isReachBottom.value = true
    }
  }, 100)
  
  onMounted(() => {
    if(elRef) el = elRef.value
      el.addEventListener("scroll", scrollListenerHandle)
  })

  onUnmounted(() => {
    el.removeEventListener("scroll", scrollListenerHandle)
  })

  return {isReachBottom,scrollTop}
}